/**
 *  Copyright 2009 Henning Teek, Ingo Renner
 *  
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *  
 *  http://www.apache.org/licenses/LICENSE-2.0
 *  
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License. 
 */
package com.googlecode.chigs.web.common.brix;

import java.io.IOException;
import java.io.InputStream;

import org.apache.wicket.Resource;
import org.apache.wicket.util.resource.AbstractResourceStream;
import org.apache.wicket.util.resource.IResourceStream;
import org.apache.wicket.util.resource.ResourceStreamNotFoundException;

import brix.BrixNodeModel;
import brix.jcr.wrapper.BrixFileNode;
import brix.jcr.wrapper.BrixNode;

import com.googlecode.chigs.web.BrixAwareApplication;

/**
 * Adress the Content of an BrixFileNode as Wicket Resource.
 * 
 * @author Ingo Renner
 * @author Henning Teek
 *
 */
public class BrixFileNodeResource extends Resource {
	private final String resourceName;
	private final BrixAwareApplication application;

	public BrixFileNodeResource(String resourceName, BrixAwareApplication application) {
		this.resourceName = resourceName;
		this.application = application;
	}

	@Override
	public IResourceStream getResourceStream() {
		return new AbstractResourceStream() {
			// must be transient, the stream itself is not serializeable
			private transient InputStream stream;

			@Override
			public void close() throws IOException {
				if (stream != null) {
					stream.close();
				}
			}

			@Override
			public InputStream getInputStream() throws ResourceStreamNotFoundException {
				BrixNodeModel model = application.getBrixLink("/" + resourceName);
				BrixNode node = model.getObject();
				BrixFileNode bfn = new BrixFileNode(node, node.getSession());
				stream = bfn.getDataAsStream();
				return stream;
			}
		};
	}
}
